<template>
  <div class="app-container">
    <el-row :gutter="24">
      <el-col :span="24">
        <el-button
          style="float: right; margin-bottom: 20px"
          type="primary"
          icon="el-icon-plus"
          :loading="loading"
          @click="handHandExam()"
        >{{ handleText }}</el-button>
      </el-col>

      <el-col :span="6" :xs="24" style="margin-bottom: 10px">
        <el-card>
          <p class="card-title">答题卡</p>
          <el-row :gutter="24" class="card-line" style="padding-left: 10px">
            <el-tag type="info">未作答</el-tag>
            <el-tag type="success">已作答</el-tag>
          </el-row>

          <div v-if="paperData.radioList!==null && paperData.radioList.length > 0">
            <p class="card-title">单选题</p>
            <el-row :gutter="24" class="card-line">
              <el-tag
                v-for="item in paperData.radioList"
                :key="item.id"
                :type="cardItemClass(item.answered, item.quId)"
                @click="handSave(item)"
              >{{ item.sort+1 }}</el-tag>
            </el-row>
          </div>

          <div v-if="paperData.multiList!==null && paperData.multiList.length > 0">
            <p class="card-title">多选题</p>
            <el-row :gutter="24" class="card-line">
              <el-tag
                v-for="item in paperData.multiList"
                :key="item.id"
                :type="cardItemClass(item.answered, item.id)"
                @click="handSave(item)"
              >{{ item.sort+1 }}</el-tag>
            </el-row>
          </div>

          <div v-if="paperData.judgeList!==null && paperData.judgeList.length > 0">
            <p class="card-title">判断题</p>
            <el-row :gutter="24" class="card-line">
              <el-tag
                v-for="item in paperData.judgeList"
                :key="item.id"
                :type="cardItemClass(item.answered, item.id)"
                @click="handSave(item)"
              >{{ item.sort+1 }}</el-tag>
            </el-row>
          </div>
        </el-card>
      </el-col>

      <el-col :span="18" :xs="24">
        <el-card class="qu-content">
          <p v-if="quData.content">{{ quData.sort + 1 }}.{{ quData.content }}</p>

          <div v-if="quData.quType === 1 || quData.quType===3">
            <el-radio-group v-model="radioValue">
              <div v-for="item in quData.answerList" :key="item.id">
                <el-radio :label="item.id">{{ item.content }}</el-radio>
              </div>
            </el-radio-group>
          </div>

          <div v-if="quData.quType === 2">
            <el-checkbox-group v-model="multiValue">
              <div v-for="item in quData.answerList" :key="item.id">
                <el-checkbox :label="item.id">{{ item.content }}</el-checkbox>
              </div>
            </el-checkbox-group>
          </div>
        </el-card>

        <div style="margin-top: 20px">
          <el-button
            v-if="showPrevious"
            type="primary"
            icon="el-icon-back"
            @click="handPrevious()"
          >上一题</el-button>

          <el-button v-if="showNext" type="warning" icon="el-icon-right" @click="handNext()">下一题</el-button>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { Loading } from 'element-ui'

export default {
  name: 'ExamProcess',
  components: {},
  data () {
    return {
      // 全屏/不全屏
      isFullscreen: false,
      showPrevious: false,
      showNext: true,
      loading: false,
      handleText: '提交',
      pageLoading: false,
      // 试卷ID
      paperId: '',
      // 当前答题卡
      cardItem: {},
      allItem: [],
      // 当前题目内容
      quData: {
        answerList: []
      },
      // 试卷信息
      paperData: {
        leftSeconds: 99999,
        radioList: [],
        multiList: [],
        judgeList: []
      },
      // 单选选定值
      radioValue: '',
      // 多选选定值
      multiValue: [],
      // 已答ID
      answeredIds: []
    }
  },
  created () {
    const workId = this.$route.query.workId
    if (typeof workId !== 'undefined') {
      this.paperId = workId
      this.getDataList(workId)
    }
  },

  methods: {
    // 获取数据列表
    getDataList (workId) {
      this.dataListLoading = true
      this.$http({
        url: this.$http.adornUrl('/workmanagement/work/getWorkDetails'),
        method: 'get',
        params: this.$http.adornParams({
          'workId': workId
        })
      }).then(({ data }) => {
        if (data && data.code === 0) {
          console.log(data)
          // 试卷内容
          this.paperData = data.work
          // 获得第一题内容
          if (this.paperData.radioList) {
            this.cardItem = this.paperData.radioList[0]
          } else if (this.paperData.multiList) {
            this.cardItem = this.paperData.multiList[0]
          } else if (this.paperData.judgeList) {
            this.cardItem = this.paperData.judgeList[0]
          }
          const that = this

          if (this.paperData.radioList) {
            this.paperData.radioList.forEach(item => {
              that.allItem.push(item)
            })
          }

          if (this.paperData.multiList) {
            this.paperData.multiList.forEach(item => {
              that.allItem.push(item)
            })
          }

          if (this.paperData.judgeList) {
            this.paperData.judgeList.forEach(item => {
              that.allItem.push(item)
            })
          }

          // 当前选定
          this.fetchQuData(this.cardItem)
        }
        this.dataListLoading = false
      })
    },
    // 答题卡样式
    cardItemClass (answered, quId) {
      if (quId === this.cardItem.id) {
        return 'warning'
      }

      if (answered) {
        return 'success'
      }

      if (!answered) {
        return 'info'
      }
    },

    /**
     * 统计有多少题没答的
     * @returns {number}
     */
    countNotAnswered () {
      let notAnswered = 0
      //   获取单选题
      if (this.paperData.radioList) {
        this.paperData.radioList.forEach(item => {
          if (!item.answered) {
            notAnswered += 1
          }
        })
      }

      //   获取多选题
      if (this.paperData.multiList) {
        this.paperData.multiList.forEach(item => {
          if (!item.answered) {
            notAnswered += 1
          }
        })
      }

      //   获取判断题
      if (this.paperData.judgeList) {
        this.paperData.judgeList.forEach(item => {
          if (!item.answered) {
            notAnswered += 1
          }
        })
      }

      return notAnswered
    },

    /**
     * 下一题
     */
    handNext () {
      const index = this.cardItem.sort + 1
      this.handSave(this.allItem[index])
    },

    /**
     * 上一题
     */
    handPrevious () {
      const index = this.cardItem.sort - 1
      this.handSave(this.allItem[index])
    },

    doHandler () {
      this.handleText = '正在提交作业，请等待...'
      this.loading = true
      this.$http({
        url: this.$http.adornUrl('/workmanagement/work/submitWork'),
        method: 'get',
        params: this.$http.adornParams({
          'workId': this.paperId
        })
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.$message({
            message: '作业提交成功，即将进入作业详情！',
            type: 'success'
          })
          this.$router.push({ name: 'manage-workResult', query: { workId: this.paperId } })
        } else {
          this.$message.error(data.msg)
        }
      })
    },

    // 交卷操作
    handHandExam () {
      const that = this

      // 交卷保存答案
      this.handSave(this.cardItem, function () {
        const notAnswered = that.countNotAnswered()

        let msg = '确认要交卷吗？'

        if (notAnswered > 0) {
          msg = '您还有' + notAnswered + '题未作答，确认要交卷吗?'
        }

        that.$confirm(msg, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          that.doHandler()
        }).catch(() => {
          that.$message({
            type: 'info',
            message: '交卷已取消，您可以继续作答！'
          })
        })
      })
    },

    // 保存答案
    handSave (item, callback) {
      if (item.id === this.allItem[0].id) {
        this.showPrevious = false
      } else {
        this.showPrevious = true
      }

      // 最后一个索引
      const last = this.allItem.length - 1

      if (item.id === this.allItem[last].id) {
        this.showNext = false
      } else {
        this.showNext = true
      }

      const answers = this.multiValue
      if (this.radioValue !== '') {
        answers.push(this.radioValue)
      }

      this.$http({
        url: this.$http.adornUrl('/workmanagement/workanswer/fillAnswer'),
        method: 'post',
        data: this.$http.adornData({
          'workId': this.paperId,
          'quId': this.cardItem.id,
          'answers': answers,
          'answer': ''
        })
      }).then(({ data }) => {
        if (data && data.code === 0) {
          // 必须选择一个值
          if (answers.length > 0) {
            // 加入已答列表
            this.cardItem.answered = true
          }

          // 最后一个动作，交卷
          if (callback) {
            callback()
          }

          // 查找详情
          this.fetchQuData(item)
        }
      })
    },

    // 试卷详情
    fetchQuData (item) {
      // 打开
      const loading = Loading.service({
        text: '拼命加载中',
        background: 'rgba(0, 0, 0, 0.7)'
      })

      // 获得详情
      this.cardItem = item
      // 查找下个详情
      this.$http({
        url: this.$http.adornUrl('/workmanagement/question/getQuestionAnswers'),
        method: 'get',
        params: this.$http.adornParams({
          'workId': this.paperId,
          'quId': item.id
        })
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.quData = data.work
          this.radioValue = ''
          this.multiValue = []
          let workData = this.paperData
          for (let key in workData) {
            let val = workData[key]
            if (val instanceof Array) {
              if (val) {
                val.forEach(v => {
                  if (v.id === item.id) {
                    this.quData.sort = v.sort
                  }
                })
              }
            }
          }
          // 填充该题目的答案
          this.quData.answerList.forEach((item) => {
            if ((this.quData.quType === 1 || this.quData.quType === 3) && item.checked) {
              this.radioValue = item.id
            }

            if (this.quData.quType === 2 && item.checked) {
              this.multiValue.push(item.id)
            }
          })

          // 关闭详情
          loading.close()
        }
      })
    }
  }
}
</script>

<style scoped>
.qu-content div {
  line-height: 30px;
}

.el-checkbox-group label,
.el-radio-group label {
  width: 100%;
}

.card-title {
  background: #eee;
  line-height: 35px;
  text-align: center;
  font-size: 14px;
}
.card-line {
  padding-left: 10px;
}
.card-line span {
  cursor: pointer;
  margin: 2px;
}

::v-deep .el-radio,
.el-checkbox {
  padding: 9px 20px 9px 10px;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  margin-bottom: 10px;
}

::v-deep .el-checkbox__inner {
  display: none;
}

::v-deep .el-radio__inner {
  display: none;
}

::v-deep .el-checkbox__label {
  line-height: 30px;
}

::v-deep .el-radio__label {
  line-height: 30px;
}
</style>

